package org.erp.procurement.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.erp.common.basic.BaseEntity;
import org.erp.procurement.constant.OrderConstant;
import org.erp.procurement.entity.bo.OrderProductDetailsAddBo;
import org.erp.procurement.entity.bo.PcOrderAddBo;
import org.erp.procurement.enums.OrderStatusEnum;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 线下后台管理订单表
 *
 * @author libin
 * @version 1.0
 * @description: 线下后台管理订单表
 * @date 2025/11/5 10:33
 **/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
@TableName(value = "pc_order", autoResultMap = true)
public class PcOrder extends BaseEntity {
    /**
     * 自增id
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 订单编号
     */
    private String orderNo;
    /**
     * 采购数量
     */
    private Integer purchaseQuantity;
    /**
     * 回收数量
     */
    private Integer recycleQuantity;
    /**
     * 回收金额
     */
    private Integer recycleAmount;
    /**
     * 退回数量
     */
    private Integer returnQuantity;
    /**
     * 售卖人id
     */
    private Long sellId;
    /**
     * 售卖人名称
     */
    private String sellName;
    /**
     * 租户id
     */
    private Long tenantId;
    /**
     * 租户名称
     */
    private String tenantName;
    /**
     * 是否代销
     */
    private Integer isSell;
    /**
     * 订单状态
     */
    private Integer status;

    public static PcOrder addBuild(PcOrderAddBo pcOrderAddBo) {
        int purchaseQuantity = pcOrderAddBo.getOrderProductDetailsAddBoList().size();
        int recycleQuantity = pcOrderAddBo.getOrderProductDetailsAddBoList().stream()
                .filter(o -> (null != o.getRecycleAmount() && 0 != o.getRecycleAmount())).toList().size();
        int recycleAmount = pcOrderAddBo.getOrderProductDetailsAddBoList().stream()
                .filter(o -> null != o.getRecycleAmount())
                .mapToInt(OrderProductDetailsAddBo::getRecycleAmount).sum();
        return PcOrder.builder()
                .orderNo(OrderConstant.PC_PREFIX + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                        + String.valueOf(Math.random()).substring(2, 6))
                .purchaseQuantity(purchaseQuantity)
                .recycleQuantity(recycleQuantity)
                .recycleAmount(recycleAmount)
                .returnQuantity(purchaseQuantity - recycleQuantity)
                .sellId(pcOrderAddBo.getSellId())
                .sellName(pcOrderAddBo.getSellName())
                .isSell(pcOrderAddBo.getIsSell())
                .status(OrderStatusEnum.TO_BE_CONFIRMED.getCode())
                .build();
    }
}
